﻿// HSS.Forms.ConnectionStringProfiles.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       ConnectionStringProfiles.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/24/2010
// ----------------------------------------------------------------------------
namespace HSS.Forms
{
	#region Using Directives
	using System;
	using System.Drawing;
	using System.Linq;
	using System.Windows.Forms;
	using HSS.Data;


	#endregion

	#region ConnectionStringProfiles
	/// <summary>
	/// Allows the user to manage their collection of <see cref="DataAccessConnection"/>'s.
	/// </summary>
	public partial class ConnectionStringProfiles : Form
	{
		#region Fields
		string lastKnown = string.Empty;
		DataAccessConnection selectedConnection;
		TextBox txtConnectionName;
		string editName;
		#endregion

		#region Constructors
		/// <summary>
		/// Constructor
		/// </summary>
		public ConnectionStringProfiles()
		{
			InitializeComponent();

			this.Shown += new EventHandler(ConnectionStringProfiles_Shown);
			AppUserConfiguration<DataAccessConnection>.Editor = typeof(ConnectionStringBuilder);
		}
		#endregion

		#region Properties
		/// <summary>
		/// Gets the currently selected <see cref="DataAccessConnection"/>.
		/// </summary>
		public DataAccessConnection SelectedConnection
		{
			get { return selectedConnection; }
		}
		#endregion

		#region Methods
		void SetButtons()
		{
			int selectedIndex = this.lsbConnections.SelectedIndex;
			if (selectedIndex >= 0)
			{
				this.btnDelete.Enabled = true;
				this.btnEdit.Enabled = true;
				this.btnSelect.Enabled = true;
			}
			else
			{
				this.btnDelete.Enabled = false;
				this.btnEdit.Enabled = false;
				this.btnSelect.Enabled = false;
			}
		}
		bool ConnectionExist(string connectionName)
		{
			int count = this.lsbConnections.Items.OfType<DataAccessConnection>().Count(c => c.Name == connectionName);
			return count > 0;
		}
		void RefreshConnections()
		{
			AppUserConfiguration<DataAccessConnection>.Refresh();

			this.lsbConnections.DataSource = AppUserConfiguration<DataAccessConnection>.Items;

			if (!string.IsNullOrEmpty(this.lastKnown))
			{
				string selectName = this.lastKnown;
				this.lastKnown = string.Empty;
				for (int i = 0; i < this.lsbConnections.Items.Count; i++)
				{
					if (((DataAccessConnection)this.lsbConnections.Items[i]).Name == selectName)
					{
						this.lsbConnections.SetSelected(i, true);
						break;
					}
				}
			}

			this.SetButtons();
		}
		void AddConnection()
		{
			var conn = AppUserConfiguration<DataAccessConnection>.CreateNew();

			if (null != conn)
			{
				var name = this.RemoveUnsupportedCharacter(conn.DataSource);
				if (AppUserConfiguration<DataAccessConnection>.Contains(name) && !string.IsNullOrEmpty(conn.InitialCatalog))
					name += "_" + conn.InitialCatalog;
				if (AppUserConfiguration<DataAccessConnection>.Contains(name))
				{
					var message = string.Format(Resources.ConnectionStringProfiles_SetNewName, name);
					var result = MessageBox.Show(message, Resources.ConnectionStringProfiles_NewConnTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
					switch (result)
					{
						case System.Windows.Forms.DialogResult.Yes:
							name = HSS.Forms.MessageService.ShowInputBox(Resources.ConnectionStringProfiles_NewConnTitle, Resources.ConnectionStringProfiles_PromptNewName, name);
							if (AppUserConfiguration<DataAccessConnection>.Contains(name))
							{
								MessageBox.Show(Resources.ConnectionStringProfiles_ConnAlreadyExists, Resources.ConnectionStringProfiles_NewConnTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
								AppUserConfiguration<DataAccessConnection>.Remove(string.Empty);
								return;
							}
							break;

						case System.Windows.Forms.DialogResult.No:
							break;

						case System.Windows.Forms.DialogResult.Cancel:
							AppUserConfiguration<DataAccessConnection>.Remove(string.Empty);
							return;
					}
				}
				conn.Name = name;
				AppUserConfiguration<DataAccessConnection>.Save();
				this.RefreshConnections();
			}
		}
		void DuplicateConnection()
		{
			if (null != selectedConnection)
			{
				var conn = new DataAccessConnection(selectedConnection);
				var name = selectedConnection.Name + "-Copy";
				conn.Name = name;
				if (AppUserConfiguration<DataAccessConnection>.Add(conn))
					this.RefreshConnections();
				else
					MessageBox.Show(Resources.ConnectionStringProfiles_CantAddDup, "Duplicate Connection", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}
		void EditConnection()
		{
			DataAccessConnection conn = AppUserConfiguration<DataAccessConnection>.Edit(selectedConnection.Name);

			if (null != conn)
				selectedConnection = conn;
			this.lastKnown = selectedConnection.Name;
			AppUserConfiguration<DataAccessConnection>.Save();
			this.RefreshConnections();
		}
		void DeleteConnection()
		{
			AppUserConfiguration<DataAccessConnection>.Remove(selectedConnection.Name);
			this.RefreshConnections();
		}
		void BeginRenameConnection()
		{
			selectedConnection = this.lsbConnections.SelectedItem as DataAccessConnection;
			editName = selectedConnection.Name;
			Rectangle r = this.lsbConnections.GetItemRectangle(this.lsbConnections.SelectedIndex);
			this.txtConnectionName.Location = new System.Drawing.Point(r.X, r.Y);
			this.txtConnectionName.Size = new System.Drawing.Size(r.Width, r.Height);
			this.txtConnectionName.Show();
			this.txtConnectionName.Text = editName;
			this.txtConnectionName.Focus();
			this.txtConnectionName.SelectAll();
			this.txtConnectionName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtConnectionName_KeyPress);
			this.txtConnectionName.Leave += new System.EventHandler(this.txtConnectionName_Leave);
		}
		bool RenameConnection(string newName)
		{
			if (editName == newName)
				return false;
			newName = RemoveUnsupportedCharacter(newName);
			if (string.IsNullOrEmpty(newName))
				newName = "NEW_Untitled";
			if (ConnectionExist(newName))
			{
				MsgBox.Show("A connection with the name [ " + newName + " ] already exists.");
				return false;
			}
			this.selectedConnection.Name = newName;
			this.lastKnown = newName;
			AppUserConfiguration<DataAccessConnection>.Save();
			return true;
		}
		void EndRenameConnection()
		{
			this.txtConnectionName.Leave -= new System.EventHandler(this.txtConnectionName_Leave);
			this.txtConnectionName.KeyPress -= new System.Windows.Forms.KeyPressEventHandler(this.txtConnectionName_KeyPress);
			this.txtConnectionName.Hide();
		}
		void SelectConnection()
		{
			this.DialogResult = DialogResult.OK;
			this.Close();
		}
		string RemoveUnsupportedCharacter(string dbConnName)
		{
			return dbConnName.Replace("(", "").Replace(")", "").Replace(":", "").Replace(".", "").Replace("<", "").Replace(">", "");
		}
		#endregion

		#region Event Handlers
		void ConnectionStringProfiles_Shown(object sender, EventArgs e)
		{
			this.RefreshConnections();

			// 
			// txtConnectionName
			// 
			this.txtConnectionName = new TextBox();
			this.txtConnectionName.Location = new System.Drawing.Point(0, 0);
			this.txtConnectionName.Size = new System.Drawing.Size(0, 0);
			this.txtConnectionName.Hide();
			this.lsbConnections.Controls.Add(this.txtConnectionName);
			this.txtConnectionName.Text = string.Empty;
			this.txtConnectionName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
			this.txtConnectionName.BackColor = SystemColors.Info;
			this.txtConnectionName.Name = "txtConnectionName";

		}
		void lsbConnections_SelectedIndexChanged(object sender, EventArgs e)
		{
			selectedConnection = this.lsbConnections.SelectedItem as DataAccessConnection;
			this.SetButtons();
		}
		void lsbConnections_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.F2)
				this.BeginRenameConnection();
		}
		void lsbConnections_DoubleClick(object sender, EventArgs e)
		{
			this.BeginRenameConnection();
		}
		void txtConnectionName_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == 13)
			{
				if (this.RenameConnection(this.txtConnectionName.Text))
					this.RefreshConnections();
				this.EndRenameConnection();
			}
			if (e.KeyChar == 27)
				this.EndRenameConnection();
		}
		void txtConnectionName_Leave(object sender, EventArgs e)
		{
			if (this.txtConnectionName.Visible)
			{
				if (this.RenameConnection(this.txtConnectionName.Text))
					this.RefreshConnections();
				this.EndRenameConnection();
			}
		}
		void btnAdd_Click(object sender, EventArgs e)
		{
			this.AddConnection();
		}
		void btnDuplicate_Click(object sender, EventArgs e)
		{
			this.DuplicateConnection();
		}
		void btnEdit_Click(object sender, EventArgs e)
		{
			this.EditConnection();
		}
		void btnDelete_Click(object sender, EventArgs e)
		{
			this.DeleteConnection();
		}
		void btnSelect_Click(object sender, EventArgs e)
		{
			this.SelectConnection();
		}
		void btnCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}
		#endregion
	}
	#endregion
}